package com.cuit.zuke.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cuit.zuke.common.util.Result;
import com.cuit.zuke.common.vo.QuarterlyDataVo;
import com.cuit.zuke.order.client.DictFeignClient;
import com.cuit.zuke.order.client.ProductFeignClient;
import com.cuit.zuke.order.client.UserFeignClient;
import com.cuit.zuke.order.mapper.AddressMapper;
import com.cuit.zuke.order.mapper.GoodsOrderDetailMapper;
import com.cuit.zuke.order.model.entity.Address;
import com.cuit.zuke.order.model.entity.GoodsOrder;
import com.cuit.zuke.order.model.entity.GoodsOrderDetail;
import com.cuit.zuke.order.model.vo.GoodsListVO;
import com.cuit.zuke.order.model.vo.GoodsOrderQueryVO;
import com.cuit.zuke.order.model.vo.GoodsOrderVO;
import com.cuit.zuke.order.service.AddressService;
import com.cuit.zuke.order.service.GoodsAndHotelService;
import com.cuit.zuke.order.service.GoodsOrderService;
import com.cuit.zuke.order.service.HotelOrderService;
import com.cuit.zuke.product.model.entity.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order/goods")
public class GoodsOrderController {

    @Autowired
    private GoodsOrderService goodsOrderService;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private DictFeignClient dictFeignClient;

    @Autowired
    private AddressService addressService;

    @Autowired
    private GoodsOrderDetailMapper goodsOrderDetailMapper;

    @Autowired
    private HotelOrderService hotelOrderService;

    @Autowired
    private GoodsAndHotelService goodsAndHotelService;

    /**
     * 带条件的分页查询
     * @param page
     * @param limit
     * @param goodsOrderQueryVO
     * @return
     */
    @GetMapping(value = "list/{page}/{limit}")
    public Result listGoodsOrder(@PathVariable Integer page,
                                 @PathVariable Integer limit,
                                 GoodsOrderQueryVO goodsOrderQueryVO){
        Page<GoodsOrderVO> voPage = goodsOrderService.listOrder(page, limit, goodsOrderQueryVO);
        return Result.ok().put("data",voPage);
    }

    /**
     * 根据id删除订单
     * @param id
     * @return
     */
    @PostMapping(value = "deleteById")
    public Result deleteGoodsOrder(@RequestBody String id){
        boolean flag = goodsOrderService.deleteById(id);
        if (flag){
            return Result.ok();
        }else {
            return Result.error("删除失败");
        }
    }

    /**
     * 处理订单，自动选择库存充裕的仓库进行发货
     * @param goodsOrderVO
     * @return
     */
    @PostMapping(value = "handle")
    public Result handleGoodsOrder(@RequestBody GoodsOrderVO goodsOrderVO){
        boolean b = goodsOrderService.handleOrder(goodsOrderVO);
        if (b){
            return Result.ok();
        }else {
            return Result.error("库存不够");
        }
    }

    /**
     * 生成商品订单
     * @param goodsId
     * @return
     */
    @PostMapping(value = "createGoodsOrder")
    public GoodsOrderVO createOrder(@RequestParam("goodsId") Long goodsId,@RequestParam("uid")String uid){
        // 生成订单
        GoodsOrder goodsOrder = goodsOrderService.generateOrder(uid);
        if (goodsOrder == null){
            return null;
        }
        // 生成订单和商品对应表
        GoodsOrderDetail goodsOrderDetail = goodsOrderService.generateOrderDetail(goodsOrder.getOrderId(), goodsId);

        // 返回goodsOrderVO
        GoodsOrderVO goodsOrderVO = new GoodsOrderVO();
        goodsOrderVO.setOrderId(goodsOrder.getOrderId());
        goodsOrderVO.setUserId(uid);
        goodsOrderVO.setUserName(userFeignClient.getUserById(uid).getUserName());
        Goods goods = productFeignClient.findByIdCli(goodsOrderDetail.getGoodsId());
        goodsOrderVO.setTotal(goods.getGoodsPrice().multiply(new BigDecimal(goodsOrderDetail.getNum())));  // 设置总价
        // 设置收货地址
        String receiptId = goodsOrder.getReceiptId();
        Address address = addressMapper.selectById(receiptId);
        goodsOrderVO.setReceipt(dictFeignClient.getNameById(address.getProvinceCode())
                +dictFeignClient.getNameById(address.getCityCode())
                +dictFeignClient.getNameById(address.getLocCode())
                +address.getDetailedAddress());
        // 添加订单的商品列表
        GoodsListVO goodsListVO = new GoodsListVO();
        goodsListVO.setGoods(productFeignClient.findByIdCli(goodsOrderDetail.getGoodsId()));
        goodsListVO.setNum(1);
        List<GoodsListVO> goodsList = new ArrayList<>();
        goodsList.add(goodsListVO);
        goodsOrderVO.setGoodsList(goodsList);
        goodsOrderVO.setStatus(goodsOrder.getStatus());
        goodsOrderVO.setCreateTime(goodsOrder.getCreateTime());
        return goodsOrderVO;
    }

    /**
     * 查询用户下所有订单
     * @param uid
     * @return
     */
    @PostMapping("/findByUid")
    public List<GoodsOrderVO> findByUid(@RequestParam("uid")String uid){
        List<GoodsOrderVO> resultList = goodsOrderService.findByUid(uid);
        return resultList;
    }

    /**
     * 用户付款成功，更改订单状态
     * @return
     */
    @PostMapping("/paySuccess")
    public GoodsOrderVO paySuccess(@RequestParam("orderId")String orderId){
        GoodsOrderVO goodsOrderVO = goodsOrderService.paySuccess(orderId);
        return goodsOrderVO;
    }

    /**
     * 用户点击取消订单，更改订单状态
     * @return
     */
    @PostMapping("/cancel/{orderId}")
    public Result cancelOrder(@PathVariable String orderId){
        GoodsOrder goodsOrder = goodsOrderService.getById(orderId);
        goodsOrder.setStatus((byte)5);
        QueryWrapper<GoodsOrder> queryWrapper = new QueryWrapper();
        queryWrapper.eq("order_id",orderId);
        goodsOrderService.update(goodsOrder,queryWrapper);
        return Result.ok();
    }

    /**
     * 获取每天的订单数量
     * @return
     */
    @GetMapping("/getWeeklyGoodsAndHotelOrderData")
    public Map<String, List<?>> getWeeklyGoodsAndHotelOrderData() {
        return goodsAndHotelService.getWeeklyGoodsAndHotelOrderData();
    }


    /**
     * 根据订单号得到订单
     * @param orderId
     * @return
     */
    @GetMapping("/findById")
    public GoodsOrderVO findById(@RequestParam String orderId){
        GoodsOrder goodsOrder = goodsOrderService.getById(orderId);

        GoodsOrderVO goodsOrderVO = new GoodsOrderVO();
        // 订单号
        goodsOrderVO.setOrderId(goodsOrder.getOrderId());
        // 用户id
        goodsOrderVO.setUserId(goodsOrder.getUserId());
        // 用户name
        goodsOrderVO.setUserName(userFeignClient.getUserById(goodsOrder.getUserId()).getUserName());
        // 发货地址
        goodsOrderVO.setShipping(goodsOrder.getShippingAddress());
        // 创建时间
        goodsOrderVO.setCreateTime(goodsOrder.getCreateTime());
        //运单号
        goodsOrderVO.setWbNO(goodsOrder.getWbNo());
        // 收货地址
        String receiptId = goodsOrder.getReceiptId();
        Address address = addressService.getById(receiptId);
        String province = dictFeignClient.getNameById(address.getProvinceCode());
        String city = dictFeignClient.getNameById(address.getCityCode());
        String loc = dictFeignClient.getNameById(address.getLocCode());
        goodsOrderVO.setReceipt(province+"-"+city+"-"+loc+"-"+address.getDetailedAddress());
        // 订单商品列表
        String orderId1 = goodsOrder.getOrderId();
        QueryWrapper<GoodsOrderDetail> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("order_id",orderId1);
        List<GoodsListVO> goodsListVOS = new ArrayList<>();
        List<GoodsOrderDetail> goodsOrderDetails = goodsOrderDetailMapper.selectList(queryWrapper1);
        Double price = 0.0;
        // 遍历中间表，得到订单下所有商品
        for (GoodsOrderDetail goodsOrderDetail : goodsOrderDetails) {
            Goods goods = productFeignClient.findByIdCli(goodsOrderDetail.getGoodsId());
            price = goods.getGoodsPrice().doubleValue() * goodsOrderDetail.getNum() + price;
            // 封装了查询的商品和对应数量的对象
            GoodsListVO goodsListVO = new GoodsListVO();
            goodsListVO.setGoods(goods);
            goodsListVO.setNum(goodsOrderDetail.getNum());
            goodsListVOS.add(goodsListVO);
//                goodsMap.put(goods,goodsOrderDetail.getNum());
        }
        goodsOrderVO.setGoodsList(goodsListVOS);
        // 总价
        goodsOrderVO.setTotal(BigDecimal.valueOf(price));
        // 完成时间
        goodsOrderVO.setFinishTime(goodsOrder.getFinishTime());
        // 状态
        goodsOrderVO.setStatus(goodsOrder.getStatus());
        return goodsOrderVO;
    }

    /**
     * 完成订单
     * @param orderId
     * @return
     */
    @PostMapping("finish/{orderId}")
    public Result finishOrder(@PathVariable String orderId){
        GoodsOrder goodsOrder = goodsOrderService.getById(orderId);
        goodsOrder.setStatus((byte)3);
        QueryWrapper<GoodsOrder> goodsOrderQueryWrapper = new QueryWrapper<>();
        goodsOrderQueryWrapper.eq("order_id",orderId);
        boolean b = goodsOrderService.update(goodsOrder, goodsOrderQueryWrapper);
        if (b){
            return Result.ok();
        }else {
            return Result.error();
        }
    }

    /**
     * 获取商品和酒店季度收益
     * @return
     */
    @GetMapping("/getQuarterlyGoodsAndHotelMoney")
    public Result getGoodsOrderAndHotelOrderOfMoney() {
        Map<String, List<?>> map = goodsAndHotelService.getQuarterlyGoodsAndHotelMoney();
        return Result.ok().put("res", map);
    }




}
